import React, { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { UserAppDetail, UserProfile } from "../../../serve/interface";
import { Button, message, Result, Spin, Splitter, SplitterProps } from "antd";
import { PlusOutlined } from "@ant-design/icons"
import { getStore, setStore } from "../../utils/store";
import EditorTree from './EditorTree'
import { apis } from "../../apis";
import { EditorMarkdown } from "./EditorMarkdown";
import { ModalTreeNode } from "./ModalTreeNode";
import { setDocBaseUrl } from "../../utils/common";

interface EditorProps {
    profile: UserProfile;
}
export const Editor = (props: EditorProps) => {
    const { profile } = props;
    const { appId, itemId } = useParams<"appId" | "itemId">();
    const app_id = Number(appId);
    const item_id = Number(itemId);
    const app = profile?.apps?.find(app => app.id === Number(appId));
    const [appDetail, setAppDetail] = useState<UserAppDetail>();
    const navigate = useNavigate();

    useEffect(() => {
        if (app) {
            apis.app_detail({ id: app_id }).then(res => {
                if (res.success) {
                    setAppDetail(res.data);
                } else {
                    message.error(res.message);
                }
            });
        }
        setDocBaseUrl(`/app/${app_id}`)
    }, [app]);

    const item = appDetail?.tree.find(i => i.id === item_id);
    const addBtn = appDetail && <ModalTreeNode btn={
        <Button type="link" size="small" icon={<PlusOutlined />}>新建文档</Button>
    } app={app} detail={appDetail} onChange={({ detail, item }) => {
        setAppDetail(detail)
        navigate(`/app/${app.id}/${item.id}`)
    }} />

    if (!profile) {
        return <div className="text-center p-10">
            <Spin size="large" />
        </div>
    }
    if (!app) {
        return <Result status="404" title="应用不存在或已删除" subTitle={
            <Link to="/"><Button type="link" size="small">点击返回</Button></Link>
        } />
    }
    return <Splitter className="container mx-auto h-[calc(100vh-64px)] border border-solid border-gray-100 border-y-0"
        onResize={size => setStore("split_size", size[0])}>
        <Splitter.Panel defaultSize={getStore("split_size")} min={200} max={500}>
            <EditorTree app={app} detail={appDetail} onChange={setAppDetail} navigate={navigate} selectKey={item_id} />
        </Splitter.Panel>
        <Splitter.Panel>
            {appDetail && (
                item ? <EditorMarkdown app_id={app_id} item={item} onUpdateTree={setAppDetail} /> : (
                    item_id
                        ? <Result
                            status="404"
                            title="文档不存在或已删除"
                            subTitle={<div>请选择其他文档 或{addBtn}</div>} />
                        : <Result status="info" title="请选择文档" subTitle={<div>或 {addBtn}</div>} />
                )
            )}
        </Splitter.Panel>
    </Splitter>
};